package com.ruoyi.xm.controller;


import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:gzh
 * @Date: 2022/4/20 20:27
 * 注意在websocket通信中只能传string
 */
@Component
@ServerEndpoint("/socket/{userId}")
public class WebSocketServer {


    private static Map<String, Session> clients = new HashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        // 从URL参数中获取用户ID
        String userId = session.getPathParameters().get("userId");
        // 将用户ID与会话关联起来
        addClient(userId, session);
        System.out.println("客户端 " + userId + " 已连接");
    }
    public static void addClient(String userId, Session session) {
        clients.put(userId, session);
    }

    // 假设你有一个方法来移除客户端会话
    public static void removeClient(String userId) {
        clients.remove(userId);
    }

    // 发送消息给指定客户端
    public static void sendMessageToSpecificClient(String userId, String message)  {
        Session session = clients.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);

            }catch (Exception ignored) {

            }
        } else {
            System.out.println("客户端 " + userId + " 不在线或会话已关闭");
        }
    }

    // 示例：发送消息给所有客户端
    public void sendMessageToAllClients(String message) throws IOException {
        for (Session session : clients.values()) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(message);
            }
        }
    }
}
